package com.onec.service.channel.service.channel.base;

import com.alibaba.fastjson.JSONObject;
import com.onec.service.api.dto.request.channel.ChannelTradeReq;
import com.onec.service.api.dto.response.channel.ChannelTradeResp;
import com.onec.service.api.enums.ResultCodeEnum;
import com.onec.service.api.enums.StatusEnum;
import com.onec.service.channel.entity.ChannelOrderDetail;
import com.onec.service.channel.service.ChannelInfoService;
import com.onec.service.channel.service.ChannelKeyService;
import com.onec.service.channel.service.ChannelMerchantService;
import com.onec.service.channel.service.ChannelOrderDetailService;
import com.onec.service.channel.service.channel.jft.util.JftProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 上游通道通用类默认实现方法
 *
 * @author ONEC
 */
public abstract class BaseChannelOrderDefaultService implements BaseChannelOrderService {

    @Autowired
    protected ChannelInfoService channelInfoService;
    @Autowired
    protected ChannelKeyService channelKeyService;
    @Autowired
    protected ChannelMerchantService channelMerchantService;
    @Autowired
    protected ChannelOrderDetailService channelOrderDetailService;

    @Value("${channel.order.callBackUrl:http://test}")
    protected String callBackUrl;
    @Value("${channel.order.frontUrl:http://test}")
    protected String frontUrl;
    @Autowired
    protected JftProperties jftProperties;


    // 实现默认方法：
    @Override
    public RoundingMode getRoundingMode() {
        return RoundingMode.HALF_UP;
    }

    @Override
    public ChannelTradeResp requestWeiXin(ChannelOrderDetail channelOrderDetail) {
        return null;
    }

    @Override
    public ChannelTradeResp requestAliPay(ChannelTradeReq channelTradeReq) {
        return null;
    }

    @Override
    public ChannelTradeResp requestUnionPay(ChannelTradeReq channelTradeReq) {
        return null;
    }

    @Override
    public ChannelTradeResp requestOpen(ChannelTradeReq channelTradeReq) {
        return null;
    }

    @Override
    public ChannelTradeResp requestHtml(ChannelOrderDetail channelOrderDetail) {

        return null;
    }

    @Override
    public ChannelTradeResp notifyOpenCardApi(HttpServletRequest request) {
        return null;
    }


    @Override
    public ChannelTradeResp notifySettleApi(HttpServletRequest request) {
        return null;
    }


    protected String getOrderCallBackUrl(String channelService) {
        return callBackUrl + channelService + "/order";
    }

    protected String getOrderFrontUrl(String channelService) {
        return frontUrl + channelService + "/front";
    }

    /**
     * 返回交易成功：同时处理订单为处理中！
     *
     * @param
     * @return
     */
    protected ChannelTradeResp respTradeChannelState(ChannelTradeResp channelTradeResp, ChannelOrderDetail orderDetail) {
        channelTradeResp.setTradeNum(orderDetail.getTradeNum());
        channelTradeResp.setSerialNum(orderDetail.getSerialNum());
        channelTradeResp.setAmount(String.valueOf(orderDetail.getAmount()));


        channelOrderDetailService.updateChannelOrderDetail(channelTradeResp);
        StatusEnum statusEnum = StatusEnum.valueOf(channelTradeResp.getStatus());
        channelTradeResp.setCode(StatusEnum.isFailed(statusEnum) ? ResultCodeEnum.FAILED.getCode() :
                ResultCodeEnum.SUCCESS.getCode());
        return channelTradeResp;
    }


    /**
     * 获取request 中的body参数：
     *
     * @param request
     * @return
     */
    public static String getPostString(HttpServletRequest request) {
        StringBuilder buffer = new StringBuilder();
        try (InputStream inputStream = request.getInputStream()) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 直接获取请请求的map 集合
     *
     * @param request
     * @return
     */
    public static Map getParameterMap(HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        Map<String, Object> returnMap = new HashMap<>();
        Iterator entries = map.entrySet().iterator();
        Map.Entry entry;
        String name;
        String value = null;
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object objValue = entry.getValue();
            if (objValue == null) {
                value = null;
            } else if (objValue instanceof String[]) {
                String[] values = (String[]) objValue;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                assert value != null;
                //截掉最后一个逗号。
                value = value.substring(0, value.length() - 1);
            } else {
                value = objValue.toString();
            }
            returnMap.put(name, value);
        }
        for (Object key : returnMap.keySet()) {
            if ((null == returnMap.get(key)) || "".equals(((String) returnMap.get(key)).trim())) {
                returnMap.put((String) key, null);
            }
        }
        return returnMap;
    }


    /**
     * 将带有&的 字符串转为json 对象
     *
     * @param jsonStr
     * @return
     */
    public static JSONObject receiveJson(String jsonStr) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotBlank(jsonStr)) {
            String[] paramPairs = jsonStr.split("&");
            if (paramPairs.length > 0) {
                for (String paramPair : paramPairs) {
                    String[] paramPairArr = paramPair.split("=");
                    if (paramPairArr.length > 1) {
                        jsonObject.put(paramPairArr[0], paramPairArr[1]);
                    }
                }
            }
        }
        return jsonObject;
    }
}
